﻿using System;
using System.IO;
using System.Text;
using Newtonsoft.Json.Linq;
using System.ComponentModel;
using System.Collections.Generic;
using System.Net;
using System.Drawing;
using Newtonsoft.Json;
using System.Windows.Forms;
using CoreShop.Model;
using System.Diagnostics;

namespace CoreShop.Library
{
    /// <summary>
    /// 创智链ai操作类
    /// </summary>
    public class CzlAIBusiness
    {
        string url = $"{GlobalConstVars.AIData.CzlAIURL}:{GlobalConstVars.AIData.CzlAIPort}";


        ///// <summary>
        ///// 启动进程
        ///// </summary>
        public void StartProcess()
        {
            //string startPath = Path.Combine(GlobalConstVars.APP_BASEDIRECTORY, "runczlai.bat");

            //using (FileStream fileStream = new FileStream(startPath, FileMode.Create, FileAccess.Write))
            //{
            //    byte[] bytes = Encoding.UTF8.GetBytes($"{Path.Combine(GlobalConstVars.APP_BASEDIRECTORY, GlobalConstVars.AIData.CzlAIPath, GlobalConstVars.AIData.CzlAIStartPath)}");
            //    fileStream.Write(bytes, 0, bytes.Length);
            //}

            //ComputerTool.ExecuteInCmdForBack(startPath);

            // 指定要运行的exe程序的路径
            string exePath = GlobalConstVars.APP_BASEDIRECTORY + GlobalConstVars.AIData.CzlAIPath + GlobalConstVars.AIData.CzlSdkFile;

            try
            {
                // 启动exe程序
                Process.Start(exePath);
            }
            catch (Exception ex)
            {
                //Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }

        /// <summary>
        /// 关闭AI程序
        /// </summary>
        public int ExistsProcess()
        {
            // 使用进程名称（不带.exe）
            string fileName = GlobalConstVars.AIData.CzlSdkFile.Replace(".exe", string.Empty);
            Process[] processes = Process.GetProcessesByName(fileName);
            return processes.Length;
        }

        ///// <summary>
        ///// 停止进程
        ///// </summary>
        public void StopProcess()
        {
            DialogTool.ApplicationKill(GlobalConstVars.AIData.CzlSdkFile.Replace(".exe", string.Empty));
        }


        /// <summary>
        /// 获取激活状态
        /// </summary>
        /// <returns></returns>
        public string GetRegister()
        {
            try
            {
                var request = WebRequest.Create(url + "/register");
                request.Method = "GET";
                var response = (HttpWebResponse)request.GetResponse();

                string content;
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    content = sr.ReadToEnd();
                }

                var status = JObject.Parse(content);

                if (status.GetValue("deviceId").Type == JTokenType.String)
                {
                    return "已激活";
                }
            }
            catch (Exception ex)
            {

            }
            return "激活失败";
        }

        /// <summary>
        /// 获取连接状态
        /// </summary>
        /// <returns></returns>
        public string GetConnectState(ref bool isConnect)
        {
            try
            {
                string content = "";
                // 连接AI
                var request = WebRequest.Create(url + "/config");
                request.Method = "GET";
                var response = (HttpWebResponse)request.GetResponse();

                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    content = sr.ReadToEnd();
                }
                var status = JObject.Parse(content);
                isConnect = true;
                return "已连接";
            }
            catch (Exception ex)
            {

            }
            return "连接失败.";
        }


        /// <summary>
        /// 获取拍图
        /// </summary>
        /// <returns></returns>
        public Image GetCameraImg()
        {
            Image result = null;
            String exceptionText = "";
            try
            {
                //var request = WebRequest.Create(url + "/predict-product-names");
                var request = WebRequest.Create(url + "/camera-images");
                request.Method = "GET";
                var response = (HttpWebResponse)request.GetResponse();
                Stream str = response.GetResponseStream();
                result = Image.FromStream(str);
                GC.Collect();
            }
            catch (Exception ex)
            {
                exceptionText = ex.ToString();
                //A_SetLog(" 错误号：Czl_GetCameraImg:" + ex.Message);
            }
            return result;
        }


        /// <summary>
        /// 发送AI识别(深圳创智链chuangzhilian)
        /// </summary>
        public List<string> GetProducts(bool logFlag,ref string msg)
        {
            string result = "";
            try
            {
                var request = WebRequest.Create(url + "/predict-product-names");
                request.Method = "GET";
                var response = (HttpWebResponse)request.GetResponse();
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    result = sr.ReadToEnd();
                }
                if (string.IsNullOrEmpty(result))
                {
                    msg = "无效";
                }
            }
            catch
            {
                msg = "异常";
            }
            if (logFlag) LogManager.WriteTxtLog(string.Format("result={0}", result));
            if (string.IsNullOrEmpty(result)) return null;
            try
            {
                List<string> codeList = new List<string>();
                var status = JObject.Parse(result);
                JArray products = status.GetValue("products") as JArray;
                foreach (var item in products)
                {
                    string sName = item.ToString();
                    string[] sCodes = sName.Split(',');
                    if (sCodes.Length > 1) codeList.Add(sCodes[0]);
                }
                msg = "正常";
                return codeList;
            }
            catch
            {
                msg = "异常";
            }
            return null;
        }

        /// <summary>
        /// 学习(深圳创智链chuangzhilian)
        /// </summary>
        public void SetFeedback(string feedback, string[] displays, JArray arrays)
        {
            try
            {
                if (string.IsNullOrEmpty(feedback)) return;
                var request = WebRequest.Create(url + "/prediction-feedback-name");
                request.ContentType = "application/json";
                request.Method = "POST";
                var payload = new JObject();
                payload["feedback"] = feedback;
                payload["displays"] = arrays;// new JArray(displays);
                payload["backpropagation"] = true;
                using (Stream requestStream = request.GetRequestStream())
                {
                    string mjson = JsonConvert.SerializeObject(payload);
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(mjson);
                    requestStream.Write(buffer, 0, buffer.Length);
                }
                var response = (HttpWebResponse)request.GetResponse();

                string content = response.StatusCode.ToString();
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    content = sr.ReadToEnd();
                }             
            }
            catch (WebException e)
            {
                using (WebResponse response = e.Response)
                {
                    HttpWebResponse httpResponse = (HttpWebResponse)response;
                    if (httpResponse !=null)
                    {
                        Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
                        using (Stream data = response.GetResponseStream())
                        using (var reader = new StreamReader(data))
                        {
                            string text = reader.ReadToEnd();
                            Console.WriteLine(text);
                        }
                    }
                }
                //Log.LogManage.Error("学习(深圳创智链chuangzhilian)错误" + e.Message);
            }
        }


        ///// <summary>
        ///// 激活
        ///// 初始化失败时候调用
        ///// </summary>
        ///// <returns></returns>
        public bool Register(string passphrase,ref string msg)
        {
            try
            {
                {
                    var request = WebRequest.Create(url + "/register");
                    request.ContentType = "application/json";
                    request.Method = "POST";
                    var payload = new JObject();
                    payload["passphrase"] = passphrase;

                    using (Stream requestStream = request.GetRequestStream())
                    {
                        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(payload.ToString());
                        requestStream.Write(buffer, 0, buffer.Length);
                    }
                    var response = (HttpWebResponse)request.GetResponse();

                    string content;
                    using (var sr = new StreamReader(response.GetResponseStream()))
                    {
                        content = sr.ReadToEnd();
                    }

                    var status = JObject.Parse(content);

                    if (status.GetValue("deviceId").Type == JTokenType.Null)
                    {
                        msg = "激活失败";
                        return false;
                    }
                }
                {
                    var request = WebRequest.Create(url + "/update-config");
                    request.Method = "POST";
                    using (Stream requestStream = request.GetRequestStream())
                    {
                        byte[] buffer = System.Text.Encoding.UTF8.GetBytes("");
                        requestStream.Write(buffer, 0, buffer.Length);
                    }

                    var response = (HttpWebResponse)request.GetResponse();

                    string content;
                    using (var sr = new StreamReader(response.GetResponseStream()))
                    {
                        content = sr.ReadToEnd();
                    }

                    if (response.StatusCode != HttpStatusCode.NoContent)
                    {
                        msg = "激活失败";
                        return false;
                    }
                }
                {
                    var request = WebRequest.Create(url + "/update-classifier");
                    request.Method = "POST";

                    var response = (HttpWebResponse)request.GetResponse();

                    string content;
                    using (var sr = new StreamReader(response.GetResponseStream()))
                    {
                        content = sr.ReadToEnd();
                    }

                    if (response.StatusCode != HttpStatusCode.NoContent)
                    {
                        msg = "激活失败";
                        return false;
                    }
                }
                msg = "已激活";
                return true;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return false;
        }

        ///// <summary>
        ///// 设置识别区域
        ///// </summary>
        ///// <returns></returns>
        public string ShowCameraAreaView()
        {
            return HttpHelper.GetSendMessage(url,"/grpc/show/camera/area", timeout: 60).MessageOrString;
        }

        ///// <summary>
        ///// 将商品上传
        ///// </summary>
        ///// <returns></returns>
        public string PluSync(List<JObject> keyValuePairs)
        {
            //主体
            JObject keyValues = new JObject();

            keyValues.Add(new JProperty("pluList", keyValuePairs));

            return HttpHelper.PostSendMessage(url,"/grpc/plu/sync", keyValues.ToJsonString(), timeout: 60).MessageOrString;
        }

        
        ///// <summary>
        ///// 标记学习接口
        ///// </summary>
        ///// <returns></returns>
        public string Mark(string code, string name, string identifyID)
        {
            JObject keyValues = new JObject();
            JObject keyValuesPlu = new JObject();

            keyValuesPlu.Add(new JProperty("code", code));
            keyValuesPlu.Add(new JProperty("name", name));
            keyValues.Add(new JProperty("identifyID", identifyID));
            keyValues.Add(new JProperty("markType", 2));

            keyValues.Add("plu", keyValuesPlu);

            return HttpHelper.PostSendMessage(url,"/grpc/ai/mark",
                keyValues.ToJsonString(), timeout: 60).MessageOrString;
        }

        ///// <summary>
        ///// 获取激活码
        ///// </summary>
        ///// <returns></returns>
        public ReturnModel GetActivateCode()
        {
            JObject keyValues = new JObject();
            return null;
            //keyValues.Add(new JProperty("branchId", InitDataModel.StaticData.userInfoData.data.baseDeviceBranchDto.branchId));
            //keyValues.Add(new JProperty("deviceNo", InitDataModel.StaticData.MacAddress));

            //return BusTool.httpTool.PostSendMessage(InitDataModel.StaticData.ApiUrl,
            //      $"{StaticStringTool.SERVER.BASE}{StaticStringTool.API.BASE_PARAM_FEIGN_GETBASEAIBIND}", keyValues.ToJsonString());
        }
    }
}
